﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Corsat.Library;
using System.Data;
using Corsat.Library.Logic;

namespace Corsat.Web.Administration
{
    public partial class SearchAndActivate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                List<Library.Item> CourseNames = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.CourseNames);
                CourseNames.Insert(0, new Library.Item());
                ddlCourseNames.DataSource = CourseNames;
                ddlCourseNames.DataTextField = "Value";
                ddlCourseNames.DataValueField = "Id";
                ddlCourseNames.DataBind();


                DataTable dtTelephones = new DataTable();
                for (int i = 0; i < 3; i++)
                    dtTelephones.Rows.Add(dtTelephones.NewRow());

                grdTelephones.DataSource = dtTelephones;
                grdTelephones.DataBind();

                List<ChosenCourse> Courses = new List<ChosenCourse>();

                Session["lstSelectedCourses"] = Courses;

                dlCourses.DataSource = Session["lstSelectedCourses"];
                dlCourses.DataBind();

                pnlChooseCourse.Visible = false;

                Session["CoursesAndDates"] = Corsat.Library.DataManager.Main.GetAllCoursesWithDates();
            }
        }

        protected void btnsearch_Click(object sender, EventArgs e)
        {

            try
            {
                lstAccounts.Items.Clear();
                FreeAccount();

                if (rdoSearchOptions.SelectedValue != "" && txtSearchValue.Text != "")
                {
                    Corsat.Library.DataManager.SearchOptions option = Library.DataManager.SearchOptions.Name;

                    switch (rdoSearchOptions.SelectedValue)
                    {
                        case "1": option = Library.DataManager.SearchOptions.Name; break;
                        case "2": option = Library.DataManager.SearchOptions.SocialSecurityNumber; break;
                        case "3": option = Library.DataManager.SearchOptions.CorsatId; break;
                    }

                    List<Library.Item> results = Corsat.Library.DataManager.Main.Search(option, txtSearchValue.Text);

                    if (results.Count > 0)
                    {
                        lstAccounts.DataSource = results;
                        lstAccounts.DataValueField = "Id";
                        lstAccounts.DataTextField = "Value";
                        lstAccounts.DataBind();
                    }
                }
            }
            catch (Exception exc)
            {

            }
        }

        protected void btnAddNewCourse_Click(object sender, EventArgs e)
        {

            pnlChooseCourse.Visible = true;
        }

        protected void btnAddCourse_Click(object sender, EventArgs e)
        {

            List<ChosenCourse> lstSelectedCourses = Session["lstSelectedCourses"] as List<ChosenCourse>;
            List<ChosenCourse> results = lstSelectedCourses.FindAll(
               delegate(ChosenCourse c)
               { return c.CourseTitleId == Convert.ToInt32(ddlCourseNames.SelectedValue); }
               );

            DataTable dtCoursesAndDates = new DataTable();

            int tempCourseLevelId = 0;
            if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                tempCourseLevelId = Convert.ToInt32(rdoLevel.SelectedValue);

            if (Session["CoursesAndDates"] != null)
                dtCoursesAndDates = Session["CoursesAndDates"] as DataTable;

            if (ddlCourseNames.SelectedItem.Text == "")
            {
                var AlertMessage = "يجب إختيار كورس للإضافة";
                lblWarning.Text = AlertMessage;
                lblWarning.Visible = true;
            }
            else
                if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedItem == null)
                {
                    var AlertMessage = "يجب تحديد مستوى لهذا الكورس";
                    lblWarning.Text = AlertMessage;
                    lblWarning.Visible = true;
                }
                else
                    if (results.Count > 0
                        &&
                        !(results[0].CourseTitleId == 10
                            &&
                            (results[0].CourseLevelId == 24 && tempCourseLevelId == 25)
                            || (results[0].CourseLevelId == 25 && tempCourseLevelId == 24)
                            )
                        )
                    {



                        var AlertMessage = "لقد تم اختيار هذا الكورس من قبل";
                        lblWarning.Text = AlertMessage;
                        lblWarning.Visible = true;
                        return;

                    }
                    else
                    {
                        lblWarning.Visible = false;

                        ChosenCourse course = new ChosenCourse();

                        course.CourseTitleId = Convert.ToInt32(ddlCourseNames.SelectedValue);

                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                            course.CourseLevelId = Convert.ToInt32(rdoLevel.SelectedValue);

                        course.CourseFullName = ddlCourseNames.SelectedItem.Text;

                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                            course.CourseFullName += " - " + rdoLevel.SelectedItem.Text;

                        // Fill in the DayId property of the chosen Course.
                        var CourseMatchCondition = "CourseTitleId = " + course.CourseTitleId.ToString();
                        if (course.CourseLevelId != null && course.CourseLevelId != 0)
                            CourseMatchCondition += " AND CourseLevelId = " + course.CourseLevelId.ToString();
                        else
                            CourseMatchCondition += " AND CourseLevelId IS NULL";

                        DataRow[] drCourse = dtCoursesAndDates.Select(CourseMatchCondition);

                        if (drCourse.Length > 0)
                            course.DayId = Convert.ToInt32(drCourse[0]["DayId"]);

                        // Check that there aren't any courses taken in that same Day.
                        List<ChosenCourse> dayResults = lstSelectedCourses.FindAll(
                           delegate(ChosenCourse c)
                           { return c.DayId == Convert.ToInt32(drCourse[0]["DayId"]); }
                           );

                        // Inform the user and terminate the process.
                        if (dayResults.Count > 0)
                        {
                            var AlertMessage = "لقد تم إختيار كورس فى يوم \"" + drCourse[0]["DayName"].ToString() + "\" بالفعل، و لا يمكن إختيار أكثر من كورس فى نفس اليوم";
                            lblWarning.Text = AlertMessage;
                            lblWarning.Visible = true;
                            return;
                        }

                        // Update the counter of the courses.
                        var CoursesCount = hfCoursesCount.Value;
                        if (String.IsNullOrEmpty(CoursesCount))
                            hfCoursesCount.Value = "1";
                        else
                            if (Convert.ToInt32(CoursesCount) < 3)
                            {
                                CoursesCount = (Convert.ToInt32(CoursesCount) + 1).ToString();
                                hfCoursesCount.Value = CoursesCount;

                                if (Convert.ToInt32(CoursesCount) == 3)
                                    btnAddNewCourse.Visible = false;
                            }

                        int CourseLevelId = 0;

                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                            CourseLevelId = Convert.ToInt32(rdoLevel.SelectedValue);

                        Corsat.Library.DataManager.Main.RegisterAccountCourse(Convert.ToInt32(lstAccounts.SelectedValue)
                            , Convert.ToInt32(ddlCourseNames.SelectedValue)
                            , CourseLevelId);

                        pnlChooseCourse.Visible = false;

                        ReloadAccount();



                    }
        }

        protected void ddlCourseNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<Library.Item> CourseLevels = Corsat.Library.DataManager.Main.GetCourseLevels(Convert.ToInt32(ddlCourseNames.SelectedValue));
            rdoLevel.DataSource = CourseLevels;
            rdoLevel.DataTextField = "Value";
            rdoLevel.DataValueField = "Id";
            rdoLevel.DataBind();

        }

        protected void dlCourses_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            Library.DataManager.Main.UnRegisterAccountCourse(
                Convert.ToInt32(lstAccounts.SelectedValue),
                Convert.ToInt32(dlCourses.DataKeys[e.Item.ItemIndex]));

            ReloadAccount();
        }

        protected void grdTelephones_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex != -1)
            {
                DropDownList ddlTeleType = (DropDownList)e.Row.FindControl("ddlTeleType");
                List<Library.Item> TeleTypes = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.TelephoneTypes);
                TeleTypes.Insert(0, new Library.Item());
                ddlTeleType.DataSource = TeleTypes;
                ddlTeleType.DataTextField = "Value";
                ddlTeleType.DataValueField = "Id";
                ddlTeleType.DataBind();
            }
        }

        protected void lstAccounts_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReloadAccount();
        }

        protected void btnActivate_Click(object sender, EventArgs e)
        {
            Account.Activate(Convert.ToInt32(lstAccounts.SelectedValue));

            ReloadAccount();
        }

        private void FreeAccount()
        {
            try
            {
                txtArabicName.Text = "";
                txtSSN.Text = "";
                txtCorsatId.Text = "";
                txtEmail.Text = "";

             
                    for (int i = 0; i < grdTelephones.Rows.Count; i++)
                    {
                        ((DropDownList)grdTelephones.Rows[i].FindControl("ddlTeleType")).SelectedItem.Selected = false;
                        
                        ((TextBox)grdTelephones.Rows[i].FindControl("tbNumber")).Text = "";
                    }

                dlCourses.DataSource = null;

                dlCourses.DataBind();
            }
            catch (Exception exc)
            { 
            
            }
        }

        private void ReloadAccount()
        {
            try
            {
                FreeAccount();

                Account a = new Account(Convert.ToInt32(lstAccounts.SelectedValue));

                txtArabicName.Text = a.ArabicName;
                txtSSN.Text = a.SSN;
                txtCorsatId.Text = a.CorsatId.ToString();
                txtEmail.Text = a.Email;

                if (a.Telephones != null)
                    for (int i = 0; i < a.Telephones.Count; i++)
                    {
                        ((DropDownList)grdTelephones.Rows[i].FindControl("ddlTeleType")).SelectedItem.Selected = false;
                        ((DropDownList)grdTelephones.Rows[i].FindControl("ddlTeleType")).Items.FindByValue(a.Telephones[i].Type.Id.ToString()).Selected = true;
                        ((TextBox)grdTelephones.Rows[i].FindControl("tbNumber")).Text = a.Telephones[i].Number;
                    }

                dlCourses.DataSource = a.Courses;
                dlCourses.DataKeyField = "CourseId";
                dlCourses.DataBind();

            }
            catch (Exception exc)
            {

            }
        }
    }
}
